#!/bin/bash

# set -ux

# service mysql stop
# rm -rf /home/mysql /etc/init.d/mysql
# rm -rf /home/mysql/{data,logs}/*

# 创建mysql 用户，解压mysql安装包
groupadd mysql &&
  useradd -d /home/mysql -r -g mysql mysql &&
  mkdir -pv /home/mysql/{data,logs} &&
  cp /root/{.bashrc,.bash_profile} /home/mysql/ &&
  tar -xvf /root/res/mysql-8.0.28-linux-glibc2.12-x86_64.tar.xz -C /home &&
  mv /home/mysql-8.0.28-linux-glibc2.12-x86_64/* /home/mysql/ &&
  rm -rf /home/mysql-8.0.28-linux-glibc2.12-x86_64

# 修改配置文件
cat > /etc/my.cnf << EOF
[client]
port=3306
socket=/tmp/mysql.sock

[mysql]
default-character-set=utf8mb4
socket=/tmp/mysql.sock

[mysqld]
port=3306
user=mysql
server_id=1
# 目录
socket=/tmp/mysql.sock
basedir=/home/mysql
datadir=/home/mysql/data
log-error=/home/mysql/logs/error.log
pid-file=/home/mysql/data/mysql.pid
# 事务
transaction_isolation=READ-COMMITTED
# 编码
character-set-server=utf8mb4
collation-server=utf8mb4_general_ci
lower_case_table_names=1
# 创建新表时将使用的默认存储引擎
default_storage_engine=InnoDB
EOF

# 拷贝配置文件
cp /etc/my.cnf /home/mysql/support-files/my-default.cnf

# 修改权限
chown -R mysql:mysql /home/mysql

# 初始化mysql，并获取密码
/home/mysql/bin/mysqld  --defaults-file=/etc/my.cnf --initialize --user=mysql &&
  cat /home/mysql/logs/error.log | grep 'password'

cat >> /etc/ld.so.conf << EOF
/home/mysql/lib
EOF

# 配置环境
cat >> /etc/profile << EOF
# mysql env
export MYSQL_HOME=/home/mysql
export PATH=\$PATH:\$MYSQL_HOME/bin
EOF

# 使生效
source /etc/profile

# 解决  libtinfo.so.5 问题
ln -s /usr/lib64/libtinfo.so.6.1 /usr/lib64/libtinfo.so.5

# 配置服务，设置开启自启，并启动
cp /home/mysql/support-files/mysql.server /etc/init.d/mysql &&
  sed -i -e '/^basedir=/c basedir=/home/mysql' \
    -e '/^datadir=/c datadir=/home/mysql/data' /etc/init.d/mysql &&
  chmod +x /etc/init.d/mysql &&
  chkconfig --add mysql &&
  chkconfig mysql on &&
  service mysql start

# 开放端口
firewall-cmd --zone=public --add-port=3306/tcp --permanent &&
  firewall-cmd --reload
